<?php
namespace app\admin\controller;

use think\Db;
use think\facade\Session;

class Index extends Base
{
	public function index()
	{
        $this->assign('menu', config('menu.'));

		return $this->fetch();
	}

    public function main()
    {
        $user = [
            '用户' => Session::get('user.name'),
            '角色' => Session::get('role.name'),
            '发布文章数量' => Db::table('content')->where('user_id', Session::get('user.id'))->count(),
            '上次登录时间' => Session::get('user.login_time'),
            '上次登录IP' => Session::get('user.login_ip'),
        ];
        $this->assign('user', $user);

        $system = [
            '用户数量' => Db::table('user')->count(),
            '栏目数量' => Db::table('column')->count(),
            '内容数量' => Db::table('content')->count(),
            '链接数量' => Db::table('link')->count(),
            '区块数量' => Db::table('block')->count(),
        ];
        $this->assign('system', $system);

        $server = [
            '运行环境' => PHP_OS.' '.$_SERVER["SERVER_SOFTWARE"],
            'Php版本' => PHP_VERSION,
            '服务器Ip' => gethostbyname($_SERVER['SERVER_NAME']),
            '上传限制' => ini_get('upload_max_filesize'),
            'Gzip压缩' => $_SERVER['HTTP_ACCEPT_ENCODING'],
        ];
        $this->assign('server', $server);

        return $this->fetch();
    }

    public function setPassword()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $password = trim($this->request->param('password/s', ''));
            if (empty($password)) {
                $this->result('', 1, '请输入密码');
            }
            
            if (!Db::table('user')->where('id', Session::get('user.id'))->setField('password', md5($password))) {
                $this->result('', 1, '修改失败');
            }

            $this->result('', 0, '修改成功');
        }
    }

    function upload()
    {   
        $file = $this->request->file('file');
        $validate = [
            'size'  =>  1024 * 1024 * cache('site')['image'],
            'ext'   =>  str_replace('|', ',', cache('site')['image_ext']),
        ];
        $info = $file->validate($validate)->move('uploads');

        if(!$info){
            $this->result('', 1, $file->getError());
        }
        
        $this->result([
            'src' => str_replace("\\", "/", '\\uploads\\' . $info->getSaveName())
        ], 0, '上传成功');
    }

    public function test()
    {
        $editor = action('admin/editor/index');
        return $editor;
    }
}
